<template>
  <view>
    <picker mode="multiSelector"
            :range="columns"
            :value="indexes"
            @columnchange="onColumnChange"
            @change="onChange"
            @cancel="onCancel">
      <view class="picker">
        {{ displayText || '请选择 仓库 / 库区 / 库位' }}
      </view>
    </picker>
  </view>
</template>

<script>
import { getTreeList } from '@/api/wm/warehouse.js'

export default {
  name: 'warehouse',
  props: {
    // 分别控制三个层级的显示模式
    warehouseDisplayMode: {
      type: String,
      default: 'name' // 'name', 'code', 'both'
    },
    locationDisplayMode: {
      type: String,
      default: 'name' // 'name', 'code', 'both'
    },
    areaDisplayMode: {
      type: String,
      default: 'name' // 'name', 'code', 'both'
    },
    // 扫描的库位编码，用于自动选中
    scannedAreaCode: {
      type: String,
      default: ''
    },
    // 默认选择的数据，用于编辑时设置默认值
    defaultSelection: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      rawTree: [],
      columns: [[], [], []],
      indexes: [0, 0, 0], // 初始化为选择第一个
      displayText: '',
      isPickerOpen: false, // 标记选择器是否打开
      lastConfirmedIndexes: [0, 0, 0] // 记录最后确认的选择
    }
  },
  watch: {
    // 监听扫描的库位编码变化
    scannedAreaCode: {
      handler(newCode) {
        if (newCode && this.rawTree.length > 0) {
          this.selectByAreaCode(newCode)
        }
      },
      immediate: true
    },
    // 监听默认选择数据变化
    defaultSelection: {
      handler(newSelection) {
        if (newSelection && this.rawTree.length > 0) {
          this.setDefaultSelection(newSelection)
        }
      },
      immediate: true
    }
  },
  async mounted() {
    await this.loadTreeData()
  },
  methods: {
    async loadTreeData() {
      try {
        const res = await getTreeList()
        
        if (res.code === 200 && res.data && res.data.length > 0) {
          // 过滤掉虚拟线边仓库
          const filteredData = res.data.filter(warehouse => warehouse.warehouseCode !== 'XBK_VIRTUAL')
          
          if (filteredData.length === 0) {
            uni.showToast({
              title: '暂无可用仓库',
              icon: 'none'
            });
            return
          }
          
          this.rawTree = filteredData.map((warehouse) => {
            const processedWarehouse = {
              id: warehouse.warehouseId,
              code: warehouse.warehouseCode,
              name: warehouse.warehouseName,
              children: (warehouse.children || []).map((location) => {
                return {
                  id: location.locationId,
                  code: location.locationCode,
                  name: location.locationName,
                  children: (location.children || []).map((area) => {
                    return {
                      id: area.areaId,
                      code: area.areaCode,
                      name: area.areaName
                    }
                  })
                }
              })
            }
            return processedWarehouse
          })
          
          this.initColumns()
          
          
          // 如果有扫描的库位编码，自动选中
          if (this.scannedAreaCode) {
            this.selectByAreaCode(this.scannedAreaCode)
          }
          
          // 如果有默认选择数据，设置默认值
          if (this.defaultSelection) {
            this.setDefaultSelection(this.defaultSelection)
          }
        } else {
          uni.showToast({
            title: res.msg || '获取仓库数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载仓库数据失败:', error)
        uni.showToast({
          title: '加载仓库数据失败',
          icon: 'none'
        });
      }
    },
    
    // 根据库位编码自动选中
    selectByAreaCode(areaCode) {
      if (!areaCode || !this.rawTree.length) {
        return
      }
      
      for (let wIndex = 0; wIndex < this.rawTree.length; wIndex++) {
        const warehouse = this.rawTree[wIndex]
        for (let lIndex = 0; lIndex < (warehouse.children || []).length; lIndex++) {
          const location = warehouse.children[lIndex]
          for (let aIndex = 0; aIndex < (location.children || []).length; aIndex++) {
            const area = location.children[aIndex]
            if (area.code === areaCode) {
              // 找到匹配的库位，更新选择
              this.indexes = [wIndex, lIndex, aIndex]
              this.lastConfirmedIndexes = [wIndex, lIndex, aIndex]
              this.updateColumns()
              this.updateDisplayText()
              this.emitSelected()
              return
            }
          }
        }
      }
      
      // 未找到匹配的库位编码
      uni.showToast({
        title: `未找到库位编码: ${areaCode}`,
        icon: 'none'
      })
    },
    
    initColumns() {
      if (this.rawTree.length === 0) {
        this.columns = [['暂无数据'], ['暂无数据'], ['暂无数据']];
        return;
      }
      
      this.updateColumns()
      this.indexes = [0, 0, 0]
      this.lastConfirmedIndexes = [0, 0, 0]
    },
    
    // 更新列数据
    updateColumns() {
      // 第一列：仓库列表
      this.columns[0] = this.rawTree.map(w => this.getDisplayText(w, 'warehouse'))
      
      // 第二列：当前选中仓库的库区列表
      const w = this.rawTree[this.indexes[0]] || { children: [] }
      this.columns[1] = (w.children || []).map(l => this.getDisplayText(l, 'location'))
      if (this.columns[1].length === 0) {
        this.columns[1] = ['无库区']
      }
      
      // 第三列：当前选中库区的库位列表
      const l = (w.children || [])[this.indexes[1]] || { children: [] }
      this.columns[2] = (l.children || []).map(a => this.getDisplayText(a, 'area'))
      if (this.columns[2].length === 0) {
        this.columns[2] = ['无库位']
      }
    },
    
    // 获取显示文本 - 根据层级使用不同的显示模式
    getDisplayText(item, type) {
      if (!item) {
        // 根据类型返回不同的默认文本
        switch (type) {
          case 'location':
            return '无库区'
          case 'area':
            return '无库位'
          default:
            return '未知'
        }
      }
      
      let displayMode = 'name'
      switch (type) {
        case 'warehouse':
          displayMode = this.warehouseDisplayMode
          break
        case 'location':
          displayMode = this.locationDisplayMode
          break
        case 'area':
          displayMode = this.areaDisplayMode
          break
      }
      
      let result = ''
      switch (displayMode) {
        case 'code':
          result = item.code || item.name || (type === 'location' ? '无库区' : type === 'area' ? '无库位' : '未知')
          break
        case 'both':
          const defaultName = type === 'location' ? '无库区' : type === 'area' ? '无库位' : '未知'
          result = `${item.name || defaultName}(${item.code || '无编码'})`
          break
        case 'name':
        default:
          result = item.name || (type === 'location' ? '无库区' : type === 'area' ? '无库位' : '未知')
          break
      }
      
      return result
    },
    
    onColumnChange(e) {
      const { column, value } = e.detail
      this.indexes[column] = value
      
      if (column === 0) {
        // 仓库改变，重置库区和库位选择
        this.indexes[1] = 0
        this.indexes[2] = 0
      } else if (column === 1) {
        // 库区改变，重置库位选择
        this.indexes[2] = 0
      }
      
      this.updateColumns()
      this.updateDisplayText()
      
      // 关键修复：在滚动选择时也发送选中事件
      // 这样用户在选择过程中就能看到实时的选中结果
      this.emitSelected()
    },
    
    onChange(e) {
      // 用户确认选择
      this.indexes = e.detail.value
      this.lastConfirmedIndexes = [...this.indexes] // 保存确认的选择
      
      // 检查选择是否完整，给出提示
      this.checkSelectionAndShowTip()
      
      this.updateDisplayText()
      this.emitSelected()
      this.isPickerOpen = false
    },
    
    // 检查选择是否完整，给出提示
    checkSelectionAndShowTip() {
      // 检查是否选择了"无库区"默认选项
      if (this.indexes[1] >= 0 && this.columns[1] && this.columns[1][this.indexes[1]] === '无库区') {
        uni.showToast({
          title: '已选择无库区',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 检查是否选择了"无库位"默认选项
      if (this.indexes[2] >= 0 && this.columns[2] && this.columns[2][this.indexes[2]] === '无库位') {
        uni.showToast({
          title: '已选择无库位',
          icon: 'none',
          duration: 2000
        })
        return
      }
    },
    
    onCancel() {
      // 用户取消选择，恢复到上次确认的选择
      this.indexes = [...this.lastConfirmedIndexes]
      this.updateColumns()
      this.updateDisplayText()
      this.emitSelected() // 发送恢复后的选择
      this.isPickerOpen = false
    },
    
    // 更新显示文本
    updateDisplayText() {
      const w = this.rawTree[this.indexes[0]]
      const l = (w?.children || [])[this.indexes[1]]
      const a = (l?.children || [])[this.indexes[2]]
      
      const warehouseText = w ? this.getDisplayText(w, 'warehouse') : ''
      
      // 检查是否选择了"无库区"默认选项
      let locationText = ''
      if (l) {
        locationText = this.getDisplayText(l, 'location')
      } else if (this.columns[1] && this.columns[1][this.indexes[1]] === '无库区') {
        locationText = '无库区'
      }
      
      // 检查是否选择了"无库位"默认选项
      let areaText = ''
      if (a) {
        areaText = this.getDisplayText(a, 'area')
      } else if (this.columns[2] && this.columns[2][this.indexes[2]] === '无库位') {
        areaText = '无库位'
      }
      
      this.displayText = [warehouseText, locationText, areaText].filter(Boolean).join(' / ')
    },
    
    // 发送选中事件
    emitSelected() {
      const w = this.rawTree[this.indexes[0]]
      const l = (w?.children || [])[this.indexes[1]]
      const a = (l?.children || [])[this.indexes[2]]
      
      // 向父组件传递选中的完整数据
      this.$emit('selected', {
        warehouse: w,
        location: l,
        area: a,
        warehouseId: w?.id,
        warehouseCode: w?.code,
        warehouseName: w?.name,
        locationId: l?.id,
        locationCode: l?.code,
        locationName: l?.name,
        areaId: a?.id,
        areaCode: a?.code,
        areaName: a?.name
      })
    },
    
    // 设置默认选择（用于编辑时）
    setDefaultSelection(selectionData) {
      if (!selectionData || !selectionData.warehouseId) {
        return
      }
      
      // 根据传入的数据查找对应的索引
      let warehouseIndex = -1
      let locationIndex = -1
      let areaIndex = -1
      
      // 查找仓库索引
      for (let i = 0; i < this.rawTree.length; i++) {
        if (this.rawTree[i].id == selectionData.warehouseId) {
          warehouseIndex = i
          break
        }
      }
      
      if (warehouseIndex >= 0) {
        const warehouse = this.rawTree[warehouseIndex]
        
        // 查找库区索引
        if (selectionData.locationId && warehouse.children && warehouse.children.length > 0) {
          for (let i = 0; i < warehouse.children.length; i++) {
            if (warehouse.children[i].id == selectionData.locationId) {
              locationIndex = i
              break
            }
          }
        }
        
        // 查找库位索引
        if (locationIndex >= 0 && selectionData.areaId && warehouse.children[locationIndex].children && warehouse.children[locationIndex].children.length > 0) {
          for (let i = 0; i < warehouse.children[locationIndex].children.length; i++) {
            if (warehouse.children[locationIndex].children[i].id == selectionData.areaId) {
              areaIndex = i
              break
            }
          }
        }
      }
      
      // 设置索引
      this.indexes = [warehouseIndex, locationIndex, areaIndex]
      this.lastConfirmedIndexes = [warehouseIndex, locationIndex, areaIndex]
      
      // 更新显示
      this.updateColumns()
      this.updateDisplayText()
    }
  }
}
</script>

<style scoped>
.picker {
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  background-color: #fff;
  text-align: center;
}
</style>